package com.cp.config;

import com.cp.properties.SwaggerProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;

/**
 * Des:
 * swagger自动配置类
 * EnableConfigurationProperties(SwaggerProperties.class) :加载 SwaggerProperties 对象
 * 到容器中
 *
 * @author XL
 * @Date 2021/9/13 9:38
 */
@Slf4j
@Configuration
@EnableSwagger2
@ConditionalOnClass(EnableSwagger2.class)
@EnableConfigurationProperties(SwaggerProperties.class)
public class CpSwaggerAutoConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;

    @Resource
    SwaggerProperties properties;

    @Bean
    public Docket createCommonDocket() {
        if (properties.isEnable()) {
            log.info("#CaptainSwaggerAutoConfiguration# 开启初始化 , 开启swagger功能");
        }
        return new Docket(DocumentationType.SWAGGER_2)
                //是否开启swagger
                .enable(properties.isEnable())
                //路径映射
                .pathMapping("/")
                //扫描路径选择
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build()
                //分组名称, 如果存在多个 Docket 实例，则每个实例都必须具有此方法提供的唯一 groupName
                .groupName(applicationName)
                //接口信息
                .apiInfo(buildInfo());
    }

    public ApiInfo buildInfo() {
        return new ApiInfoBuilder()
                .title(applicationName)
                .version(properties.getOpenApiVersion())
                .description(StringUtils.isBlank(properties.getDescription()) ? applicationName : properties.getDescription())
                .build();
    }
}
